package com.example.myapplication1;

import android.app.Dialog;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.example.myapplication1.db.DatabaseHelper;
import com.example.myapplication1.utils.PreferenceManager;

import java.util.Map;

public class ClassroomActivity extends AppCompatActivity {
    private static final String TAG = "ClassroomActivity";
    private DatabaseHelper databaseHelper;
    private PreferenceManager preferenceManager;
    private TextView catFoodStockText;
    private TextView freezeDriedStockText;
    private TextView catTreatsStockText;
    private Map<String, Integer> userFeedStock;
    private long userId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        try {
            super.onCreate(savedInstanceState);
            Log.d(TAG, "正在创建教学楼页面");
            setContentView(R.layout.activity_classroom);

            // 初始化数据库和PreferenceManager
            databaseHelper = new DatabaseHelper(this);
            preferenceManager = new PreferenceManager(this);
            userId = preferenceManager.getUserId();

            if (userId <= 0) {
                Log.e(TAG, "Invalid user ID: " + userId);





                Toast.makeText(this, "用户未登录或ID无效", Toast.LENGTH_SHORT).show();
                finish();
                return;
            }

            // 设置返回按钮
            ImageButton backButton = findViewById(R.id.back_button);
            backButton.setOnClickListener(v -> finish());

            // 初始化视图
            initViews();
            
            // 加载用户饲料库存
            loadUserFeedStock();
            
            // 设置喂养按钮点击事件
            setupFeedButtons();

            // 加载猫咪图片
            loadCatImages();

        } catch (Exception e) {
            Log.e(TAG, "创建教学楼页面时出错: " + e.getMessage());
            Toast.makeText(this, "页面加载失败", Toast.LENGTH_SHORT).show();
            finish();
        }
    }

    private void initViews() {
        catFoodStockText = findViewById(R.id.cat_food_stock);
        freezeDriedStockText = findViewById(R.id.freeze_dried_stock);
        catTreatsStockText = findViewById(R.id.cat_treats_stock);

        // 设置喂养按钮点击事件
        Button feedXiaohuihuiButton = findViewById(R.id.feed_xiaohuihui_button);
        Button feedXiaobaiButton = findViewById(R.id.feed_xiaobai_button);
        Button feedDajuButton = findViewById(R.id.feed_daju_button);

        feedXiaohuihuiButton.setOnClickListener(v -> showFeedDialog(31, "小灰灰"));
        feedXiaobaiButton.setOnClickListener(v -> showFeedDialog(32, "小白"));
        feedDajuButton.setOnClickListener(v -> showFeedDialog(33, "大橘"));
    }

    private void loadUserFeedStock() {
        userFeedStock = databaseHelper.getUserFeedStock(userId);
        Log.d(TAG, "loadUserFeedStock - Current feed stock: " + userFeedStock.toString());
        
        // 更新库存显示
        if (userFeedStock != null) {
            catFoodStockText.setText(userFeedStock.getOrDefault("营养猫粮", 0) + "份");
            freezeDriedStockText.setText(userFeedStock.getOrDefault("小猫冻干", 0) + "份");
            catTreatsStockText.setText(userFeedStock.getOrDefault("营养猫条", 0) + "份");
        } else {
            Log.e(TAG, "Failed to load user feed stock - userFeedStock is null");
            catFoodStockText.setText("0份");
            freezeDriedStockText.setText("0份");
            catTreatsStockText.setText("0份");
        }
    }

    private void setupFeedButtons() {
        // 已在initViews中设置
    }

    private void loadCatImages() {
        try {
            ImageView xiaohuihuiImage = findViewById(R.id.cat_xiaohuihui_image);
            ImageView xiaobaiImage = findViewById(R.id.cat_xiaobai_image);
            ImageView dajuImage = findViewById(R.id.cat_daju_image);

            if (xiaohuihuiImage == null || xiaobaiImage == null || dajuImage == null) {
                Log.e(TAG, "Failed to initialize cat ImageViews");
                throw new IllegalStateException("One or more cat ImageViews not found");
            }

            Log.d(TAG, "Setting cat images...");
            
            // 获取资源ID
            int xiaohuihuiResourceId = getResources().getIdentifier("cat_xiaohuihui", "drawable", getPackageName());
            int xiaobaiResourceId = getResources().getIdentifier("cat_xiaobai", "drawable", getPackageName());
            int dajuResourceId = getResources().getIdentifier("cat_daju", "drawable", getPackageName());

            if (xiaohuihuiResourceId == 0 || xiaobaiResourceId == 0 || dajuResourceId == 0) {
                Log.e(TAG, "One or more cat images not found in resources");
                Toast.makeText(this, "无法加载猫咪图片", Toast.LENGTH_SHORT).show();
                return;
            }

            xiaohuihuiImage.setImageResource(xiaohuihuiResourceId);
            xiaobaiImage.setImageResource(xiaobaiResourceId);
            dajuImage.setImageResource(dajuResourceId);

            // 确保图片可见性
            xiaohuihuiImage.setVisibility(View.VISIBLE);
            xiaobaiImage.setVisibility(View.VISIBLE);
            dajuImage.setVisibility(View.VISIBLE);

        } catch (Exception e) {
            Log.e(TAG, "Error in loadCatImages: " + e.getMessage());
            Toast.makeText(this, "加载猫咪图片时出错", Toast.LENGTH_SHORT).show();
        }
    }

    private void showFeedDialog(int catId, String catName) {
        Dialog dialog = new Dialog(this);
        dialog.setContentView(R.layout.dialog_feed);
        dialog.setCancelable(true);

        TextView titleText = dialog.findViewById(R.id.dialog_title);
        titleText.setText("喂养 " + catName);

        // 获取输入框和库存显示
        TextView catFoodStockText = dialog.findViewById(R.id.cat_food_stock_text);
        TextView freezeDriedStockText = dialog.findViewById(R.id.freeze_dried_stock_text);
        TextView catTreatsStockText = dialog.findViewById(R.id.cat_treats_stock_text);

        // 显示当前库存
        catFoodStockText.setText(getString(R.string.remaining_format, userFeedStock.getOrDefault("营养猫粮", 0)));
        freezeDriedStockText.setText(getString(R.string.remaining_format, userFeedStock.getOrDefault("小猫冻干", 0)));
        catTreatsStockText.setText(getString(R.string.remaining_format, userFeedStock.getOrDefault("营养猫条", 0)));

        EditText catFoodAmount = dialog.findViewById(R.id.cat_food_amount);
        EditText freezeDriedAmount = dialog.findViewById(R.id.freeze_dried_amount);
        EditText catTreatsAmount = dialog.findViewById(R.id.cat_treats_amount);

        Button cancelButton = dialog.findViewById(R.id.btn_cancel);
        Button confirmButton = dialog.findViewById(R.id.btn_confirm);

        cancelButton.setOnClickListener(v -> dialog.dismiss());
        confirmButton.setOnClickListener(v -> {
            try {
                // 获取输入的数量
                String catFoodStr = catFoodAmount.getText().toString();
                String freezeDriedStr = freezeDriedAmount.getText().toString();
                String catTreatsStr = catTreatsAmount.getText().toString();

                // 检查是否至少输入了一个数量
                if (TextUtils.isEmpty(catFoodStr) && 
                    TextUtils.isEmpty(freezeDriedStr) && 
                    TextUtils.isEmpty(catTreatsStr)) {
                    Toast.makeText(this, "请至少输入一种饲料的数量", Toast.LENGTH_SHORT).show();
                    return;
                }

                // 验证输入数量是否合法
                boolean isValid = true;
                String errorMessage = "";

                // 检查营养猫粮
                if (!TextUtils.isEmpty(catFoodStr)) {
                    int amount = Integer.parseInt(catFoodStr);
                    int stock = userFeedStock.getOrDefault("营养猫粮", 0);
                    if (amount <= 0) {
                        isValid = false;
                        errorMessage = "营养猫粮数量必须大于0";
                    } else if (amount > stock) {
                        isValid = false;
                        errorMessage = "营养猫粮库存不足";
                    }
                }

                // 检查小猫冻干
                if (isValid && !TextUtils.isEmpty(freezeDriedStr)) {
                    int amount = Integer.parseInt(freezeDriedStr);
                    int stock = userFeedStock.getOrDefault("小猫冻干", 0);
                    if (amount <= 0) {
                        isValid = false;
                        errorMessage = "小猫冻干数量必须大于0";
                    } else if (amount > stock) {
                        isValid = false;
                        errorMessage = "小猫冻干库存不足";
                    }
                }

                // 检查营养猫条
                if (isValid && !TextUtils.isEmpty(catTreatsStr)) {
                    int amount = Integer.parseInt(catTreatsStr);
                    int stock = userFeedStock.getOrDefault("营养猫条", 0);
                    if (amount <= 0) {
                        isValid = false;
                        errorMessage = "营养猫条数量必须大于0";
                    } else if (amount > stock) {
                        isValid = false;
                        errorMessage = "营养猫条库存不足";
                    }
                }

                if (!isValid) {
                    Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT).show();
                    return;
                }

                // 处理喂养
                boolean success = true;

                // 处理营养猫粮
                if (!TextUtils.isEmpty(catFoodStr)) {
                    int amount = Integer.parseInt(catFoodStr);
                    if (amount > 0) {
                        success &= databaseHelper.recordFeeding(userId, catId, "营养猫粮", amount);
                    }
                }

                // 处理小猫冻干
                if (!TextUtils.isEmpty(freezeDriedStr)) {
                    int amount = Integer.parseInt(freezeDriedStr);
                    if (amount > 0) {
                        success &= databaseHelper.recordFeeding(userId, catId, "小猫冻干", amount);
                    }
                }

                // 处理营养猫条
                if (!TextUtils.isEmpty(catTreatsStr)) {
                    int amount = Integer.parseInt(catTreatsStr);
                    if (amount > 0) {
                        success &= databaseHelper.recordFeeding(userId, catId, "营养猫条", amount);
                    }
                }

                if (success) {
                    Toast.makeText(this, "喂养成功！", Toast.LENGTH_SHORT).show();
                    // 重新加载库存
                    loadUserFeedStock();
                    dialog.dismiss();
                } else {
                    Toast.makeText(this, "喂养失败，请稍后再试", Toast.LENGTH_SHORT).show();
                }
            } catch (NumberFormatException e) {
                Toast.makeText(this, "请输入有效的数量", Toast.LENGTH_SHORT).show();
            } catch (Exception e) {
                Log.e(TAG, "喂养时出错: " + e.getMessage());
                Toast.makeText(this, "操作失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });

        dialog.show();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (databaseHelper != null) {
            databaseHelper.close();
        }
    }
} 